package com.example.hyclipboard;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class DataStore {
	public static void saveData(Context context, String dataName, String data) {
		FileOutputStream fos;
		BufferedWriter writer = null;
		Log.d("TAG", "onCreate: " + data);
		try {
			/**
			 * openFileOutput(String name, int mode)
			 * name: 输出流在文件系统中的名称（文件名）
			 * mode: 输出模式 MODE_PRIVATE(default), MODE_APPEND
			 */
			fos = context.openFileOutput(dataName, Context.MODE_PRIVATE);
			writer = new BufferedWriter(new OutputStreamWriter(fos));
			writer.write(data);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String saveData(String dataName, Bitmap bitmap) {
		File appDir = new File(Environment.getExternalStorageDirectory().getPath());
		if (!appDir.exists()) {
			appDir.mkdir();
		}
		String fileName = dataName + ".jpg";
		File file = new File(appDir, fileName);
		try {
			FileOutputStream fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
			return file.getAbsolutePath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		/*
		版权声明：本文为CSDN博主「码虫韩小呆」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
		原文链接：https://blog.csdn.net/xiangshiweiyu_hd/article/details/82779619
		*/
	}

	public static String loadData(Context context, String dataName) {
		FileInputStream fis;
		BufferedReader reader = null;
		StringBuilder content = new StringBuilder();
		try {
			fis = context.openFileInput(dataName);
			reader = new BufferedReader(new InputStreamReader(fis));
			String line = "";
			while ((line = reader.readLine()) != null) {
				content.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content.toString();
	}

	public static Bitmap loadData(Context context, Uri uri) {
		InputStream inputStream = null;
		Bitmap bitmap;
		try {
			inputStream = context.getContentResolver().openInputStream(uri);
			bitmap = BitmapFactory.decodeStream(inputStream);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
